//
//  LoginViewController.m
//  TaxDealPlatform
//
//  Created by Zhengtong on 15/5/5.
//  Copyright (c) 2015年 Zhengtong. All rights reserved.
//

#import "LoginViewController.h"
#import <AFNetworking.h>
#import "JNTDataRequestTools.h"
#import "NSObject+ToolObject.h"
#import "JNTTabBarController.h"
#import "UIBarButtonItem+ZTItem.h"
#import "JNTHomeViewController.h"
#import "homeModel.h"
#import <AdSupport/AdSupport.h>
#define denglu  android/checkLogin
#define APP_DEF [NSUserDefaults standardUserDefaults]
#define TOKEN_KEY @"token"
#define TIME_KEY @"time_key"
#define USER_NAME @"userName"
#import "CurrentUserInfo.h"
@interface LoginViewController ()

@property (weak, nonatomic) IBOutlet UIImageView *topImageView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollerView;
@property (weak, nonatomic) IBOutlet UITextField *userNameField;
@property (weak, nonatomic) IBOutlet UITextField *passerWordField;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
- (IBAction)loginBtnClick:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UIView *myView;
@property (weak, nonatomic) IBOutlet UIButton *pwdBtn;
- (IBAction)forgetBtnClick:(UIButton *)sender;
@property (weak, nonatomic) IBOutlet UILabel *label1;
@property (weak, nonatomic) IBOutlet UILabel *label2;
@property (nonatomic, strong) UIImageView *myImageView;

@property (nonatomic, strong) NSMutableArray *dataSourceMArr;   //存储Model的数组


@end

@implementation LoginViewController

-(void)dealloc
{
    [self removeNotification];
}





- (void)viewDidLoad {
    [super viewDidLoad];
    
     [self removeNotification];
    [self addKeyBoardNotification];
    [self setUpNavgationBar];
    
    self.myImageView = [[UIImageView alloc]initWithFrame:kRect(0, 0, kScreenWidth, kScreenHeight)];
    self.myImageView.image = [UIImage imageNamed:@"login_bg"];
    [self.view addSubview:self.myImageView];
//    将视图添加在最底部
    [self.view sendSubviewToBack:self.myImageView];
    
    self.scrollerView.frame = CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT);
    
    UIImage *img = [UIImage imageNamed:@"login_ic_logo"];
    if (DEVICE_HEIGHT > 480) {
        self.topImageView.frame = CGRectMake((DEVICE_WIDTH - img.size.width)*0.5, 70, img.size.width, img.size.height);
        
    }else{
        self.topImageView.frame  = CGRectMake((DEVICE_WIDTH - 80)*0.5, 70, 80, 85);
    }
    self.myView.frame = CGRectMake(0, CGRectGetMaxY(self.topImageView.frame)+20, DEVICE_WIDTH, 104);
    
    self.userNameField.frame = CGRectMake(112, self.userNameField.y, DEVICE_WIDTH-120, 30);
    
    self.passerWordField.frame = CGRectMake(112, 65, DEVICE_WIDTH-120, 30);
    
    self.loginBtn.frame = CGRectMake(30, CGRectGetMaxY(self.myView.frame)+40, DEVICE_WIDTH - 60, 44);
    
    self.pwdBtn.frame = CGRectMake(DEVICE_WIDTH-105, CGRectGetMaxY(self.loginBtn.frame)+10, 90, 40);
    
    self.label1.frame = CGRectMake(0, self.label1.y, DEVICE_WIDTH, 1);
    self.label2.frame = CGRectMake(0, self.label2.y, DEVICE_WIDTH, 1);
    
 
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = YES;
    if ([CurrentUserInfo sharedCurrentUserInfo].userName) {
        
        self.userNameField.text = [CurrentUserInfo sharedCurrentUserInfo].userName;
        self.passerWordField.text = [CurrentUserInfo sharedCurrentUserInfo].password;
        NSLog(@"------------%@",self.userNameField.text);
    }
}
#pragma mark - 设置导航条
- (void)setUpNavgationBar
{
    self.navigationController.navigationBar.translucent = NO;
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"上栏"] forBarMetrics:UIBarMetricsDefault];
//    self.navigationItem.title = @"通号移动云平台";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    self.navigationItem.rightBarButtonItem =  [UIBarButtonItem rightBarButtonItemTarget:self title:@"退出" action:@selector(rightBtnClick) forControlEvents:UIControlEventValueChanged];
}

//退出该应用
- (void)rightBtnClick
{
    JNTHomeViewController *homeVC = [[JNTHomeViewController alloc]init];
    homeVC.dataSourceMArr = self.dataSourceMArr;
    [self.navigationController pushViewController:homeVC animated:YES];
}


- (IBAction)loginBtnClick:(UIButton *)sender {

        //POST请求
       NSString *url = @"http://111.206.82.216:8050/JBaas/android/checkLogin?authCode=APP*JNT@2015E0298TR";
   
   
        NSDictionary *mdic = [NSDictionary dictionaryWithObjectsAndKeys:self.userNameField.text,@"username",self.passerWordField.text,@"password",nil];
//                      NSLog(@"%@",mdic);
    [JNTDataRequestTools postFetchDataWithUrlString:url paramenters:mdic success:^(id data) {
        // 请求成功，解析数据
        NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//            NSLog(@"%@",resultDic);
        NSDictionary *myResultDic = resultDic[@"record"];
//                NSLog(@"myResultDic==%@",myResultDic);
        NSArray *modulesArr = myResultDic[@"modules"];
        for (NSDictionary *dataDic in modulesArr) {
        
                homeModel *model = [[homeModel alloc] init];
                [model setValuesForKeysWithDictionary:dataDic];
                NSLog(@"name===%@",model.name);
                
                [self.dataSourceMArr addObject:model];
            }
       

            int mrcode = [[resultDic objectForKey:@"success"] intValue];

//              NSLog(@"===%@",resultDic);
              if (!mrcode){
             
               NSLog(@"密码错误");
                  
              
              }else{
                  
                  [CurrentUserInfo sharedCurrentUserInfo].userName = self.userNameField.text;
                  [CurrentUserInfo sharedCurrentUserInfo].password = self.passerWordField.text;
                  
                  //代码能走到这里说明已经登录成功
                  NSDictionary * dicToken = [resultDic objectForKey:@"pageData"];
                  NSString *token = [dicToken objectForKey:@"password"];//NSString *token
                  float time = [[resultDic objectForKey:@"time"] floatValue];
                  NSDate *now = [NSDate date];
                  NSDate *endTime = [now dateByAddingTimeInterval:time];
                  [APP_DEF setObject:token forKey:TOKEN_KEY];
                  [APP_DEF setObject:endTime forKey:TIME_KEY];
                  [APP_DEF setObject:self.userNameField.text  forKey:USER_NAME];//存储当前登录的用户名
                  [APP_DEF synchronize];
                  
                  NSLog(@"%@", self.dataSourceMArr);
                  
                  
                  JNTHomeViewController *homeVC = [[JNTHomeViewController alloc]init];
                  homeVC.dataSourceMArr = self.dataSourceMArr;
                  
//                 [self.navigationController pushViewController:homeVC animated:YES];
                  JNTTabBarController *vc = [[JNTTabBarController alloc]init];
                  vc.dataSourceMArr = self.dataSourceMArr;
                  vc.isFirst = YES;
                  [self.navigationController pushViewController:vc animated:YES];
                  
              }

        } fail:^{
        
        NSLog(@"话题列表请求失败");
    } view:self.view];
  
}
//手机号码的正则表达式
- (BOOL) isMobile:(NSString *)mobileNumbel{
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189,181(增加)
     */
    NSString * MOBIL = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     10         * 中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";
    /**
     15         * 中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         * 中国电信：China Telecom
     21         * 133,1349,153,180,189,181(增加)
     22         */
    NSString * CT = @"^1((33|53|8[019])[0-9]|349)\\d{7}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBIL];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if (([regextestmobile evaluateWithObject:mobileNumbel]
         || [regextestcm evaluateWithObject:mobileNumbel]
         || [regextestct evaluateWithObject:mobileNumbel]
         || [regextestcu evaluateWithObject:mobileNumbel])) {
        return YES;
    }
    
    return NO;
}

//判断密码是否为6到12位的字母或者数字
- (BOOL)isPassword:(NSString *)password
{
    NSString *      regex = @"(^[A-Za-z0-9]{6,20}$)";
    NSPredicate *   pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    return [pred evaluateWithObject:password];
}

//判断名字是否为2到10个字节的中文或者汉字
- (BOOL) validateNickname:(NSString *)nickname
{
    NSString *nicknameRegex = @"[\u4e00-\u9fa5_a-zA-Z0-9_]{2,10}";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:nickname];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}






- (IBAction)forgetBtnClick:(UIButton *)sender {
    
//    ZTForgetPswController *forget = [[ZTForgetPswController alloc] init];
//    forget.hidesBottomBarWhenPushed = YES;
//    [self.navigationController pushViewController:forget animated:YES];

}

#pragma mark  - textFieldDelegate -
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.userNameField) {
        [self.passerWordField resignFirstResponder];
       
    }else if (textField == self.passerWordField)
    {
        [self.userNameField resignFirstResponder];
        
    }
    [self.scrollerView setContentOffset:CGPointMake(0, 100) animated:YES];
    
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField;
{
    [textField resignFirstResponder];
    [self.scrollerView setContentOffset:CGPointMake(0, 0) animated:YES];
    return YES;
}
-(void)keyBoarHide
{
    [self.passerWordField resignFirstResponder];
    [self.userNameField resignFirstResponder];
    [self.scrollerView setContentOffset:CGPointMake(0, 0) animated:YES];
}




- (NSMutableArray *)dataSourceMArr{
    
    if (!_dataSourceMArr) {
        
        _dataSourceMArr = [NSMutableArray array];
    }
    return _dataSourceMArr;
}










@end
//
//
